import React from 'react'
import { Upload, Table, Progress, Popconfirm, Button, message } from 'antd'
import { PlusCircleFilled, DeleteOutlined, DownloadOutlined } from '@ant-design/icons'
import { uploadServiceUrl, luanchTask, getTaskStatus, getDownloadUrl } from '@utils/api'
import { checkType } from '@utils/upload'
const { Dragger } = Upload

function NormalUpload({ type, fetchCount }) {
  const initialState = {
    fileList: [],
    fileName: '',
    targetId: '',
    process: '未上传',
    percent: 5,
    startConvert: false,
  }

  const [state, dispatch] = React.useReducer((state, action) => {
    console.log('action', action)
    switch (action.type) {
      // 重新赋值
      case 'clear':
        return initialState
      default:
        const newState = Object.assign({}, state, action.payload)
        return newState
    }
  }, initialState)
  const { targetId, process, fileName, percent } = state

  // 上传参数
  const uploadProps = {
    name: 'file',
    multiple: false,
    accept: type.accept,
    showUploadList: false,
    action: uploadServiceUrl,
    beforeUpload: (file) => {
      // 校验文件类型
      if (checkType(file, type)) {
        message.error(`文件类型错误，请重新上传格式为 ${type.accept} 的文件！`)
        dispatch({ payload: { fileList: [] } })
        return false
      }
    },
    onChange: (change) => {
      const {
        file: { status, response, percent, name },
      } = change
      console.log('response', response)

      if (status === 'uploading') {
        dispatch({
          payload: {
            percent: percent,
            process: '上传中',
            fileName: name,
          },
        })
      }

      if (status === 'done') {
        dispatch({
          payload: {
            percent: percent,
            process: '上传完成',
            targetId: response ? response.target : '',
          },
        })
        message.success(`${change.file.name}上传成功`)
      } else if (status === 'error') {
        dispatch({
          payload: {
            percent: percent,
            process: '上传失败',
            targetId: response ? response.target : '',
          },
        })
        message.error(`${change.file.name}上传失败`)
      }
    },
    onDrop: (e) => {
      console.log('Dropped files', e.dataTransfer.files)
    },
  }

  const columns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      align: 'center',
    },
    {
      title: '进度栏',
      dataIndex: 'percent',
      key: 'percent',
      align: 'center',
      render: (text, record) => (
        <div>
          <Progress
            // strokeColor={{
            //   '0%': '#108ee9',
            //   '100%': '#87d068',
            // }}
            percent={percent}
            size='small'
            style={{ width: 200, fontSize: 14 }}
            status={process.indexOf('失败') === -1 ? '' : 'exception'}
          />
          <span style={{ fontSize: 14, marginLeft: 8 }}>{process}</span>
        </div>
      ),
    },
    {
      title: '操作栏',
      dataIndex: '',
      key: 'action',
      align: 'center',
      render: (_, record) => (
        <div>
          {process === '转换完成' && (
            <a href={getDownloadUrl(targetId)}>
              <DownloadOutlined style={{ fontSize: 18, marginRight: 12 }} />
            </a>
          )}
          <Popconfirm title='确定删除?' okText='是' cancelText='否' onConfirm={() => handleDelete(record.key)}>
            <DeleteOutlined style={{ fontSize: 18 }} />
          </Popconfirm>
        </div>
      ),
    },
  ]

  // 处理删除
  const handleDelete = (key) => {
    // 暂时全删
    dispatch({ type: 'clear' })
  }

  // 处理重新开始
  const handleRestart = () => {
    dispatch({ type: 'clear' })
  }

  // 处理开始转换
  const handleConvert = async () => {
    // 先调用一次转换次数校验
    const overCount = await fetchCount(true)
    if (overCount) return

    // 参数
    const param = {
      convertType: type.exportType,
      target: targetId,
    }

    // 调用启动转换任务接口
    const data = await luanchTask(param)
    if (!data) {
      return dispatch({
        payload: {
          process: '开始转换失败',
        },
      })
    }

    dispatch({
      payload: {
        startConvert: true,
        process: '开始转换',
        percent: 10,
      },
    })

    const { status, code, message: msg } = data
    if (status === true) {
      if (code === -1) {
        // 转换失败
        dispatch({
          payload: {
            process: '转换失败',
          },
        })
        return
      } else if (code === 0) {
        // 转换未开始：这种情况继续查询
        dispatch({
          payload: {
            process: '转换未开始',
          },
        })
      } else if (code === 1) {
        // 转换中：这种情况继续查询
        dispatch({
          payload: {
            process: '转换中',
          },
        })
      } else if (code === 2) {
        // 转换成功：关闭循环定时器
        dispatch({
          payload: {
            process: '转换完成',
          },
        })
        message.success('转换完成！')
      } else if (code === 4) {
        // 超出IP限制
        message.error(msg)
        dispatch({
          payload: {
            process: '转换失败',
          },
        })
        return
      }
    } else if (status === false) {
      // 请求失败
      message.error(msg)
      dispatch({
        payload: {
          process: '请求失败',
        },
      })
      return
    }

    // 查询状态
    queryConvertResult()
  }

  const queryConvertResult = () => {
    // 参数
    const param = {
      convertType: type.exportType,
      target: targetId,
    }
    // 查询转换结果
    const intervalFetch = setInterval(async () => {
      // 调用状态查询接口
      let data
      try {
        data = await getTaskStatus(param)
      } catch (e) {
        clearInterval(intervalFetch)
      }

      if (!data) {
        // 转换失败
        dispatch({
          payload: {
            process: '查询状态失败',
          },
        })
        clearInterval(intervalFetch)
        return
      }

      const { status, code, message: msg } = data
      if (status === true) {
        if (code === -1) {
          // 转换失败
          dispatch({
            payload: {
              process: '转换失败',
            },
          })
          clearInterval(intervalFetch)
        } else if (code === 0) {
          // 转换未开始：这种情况继续查询
          dispatch({
            payload: {
              process: '转换未开始',
            },
          })
        } else if (code === 1) {
          // 转换中：这种情况继续查询
          dispatch({
            payload: {
              process: '转换中',
              percent: 70,
            },
          })
        } else if (code === 2) {
          // 转换成功：关闭循环定时器
          message.success('转换完成！')
          dispatch({
            payload: {
              process: '转换完成',
              percent: 100,
            },
          })
          clearInterval(intervalFetch)
        } else if (code === 4) {
          // 超出IP限制
          message.error(msg)
          dispatch({
            payload: {
              process: '转换失败',
            },
          })
          clearInterval(intervalFetch)
        }
      } else if (status === false) {
        // 请求失败
        message.error(msg)
        dispatch({
          payload: {
            process: '请求失败',
          },
        })
        clearInterval(intervalFetch)
      }
    }, 1000)
  }

  return (
    <div>
      {/* 上传文件 */}
      <div id='file-upload' style={{ display: fileName === '' ? 'block' : 'none' }}>
        <span>
          <Dragger {...uploadProps}>
            <p className='ant-upload-drag-icon'>
              <PlusCircleFilled className='pluscircle-icon' />
            </p>
            <p className='ant-upload-text'>选择文件</p>
          </Dragger>
        </span>
      </div>

      {/* 文件列表 */}
      <div id='upload-list' style={{ display: fileName !== '' ? 'block' : 'none' }}>
        <Table columns={columns} dataSource={[{ key: fileName, fileName, percent, process }]} pagination={false} />

        <div>
          {process === '上传完成' && (
            <Button className='transform-button' type='primary' onClick={() => handleConvert()}>
              开始转换
            </Button>
          )}

          {process === '转换完成' && (
            <>
              <Button
                className='transform-button'
                type='primary'
                onClick={() => handleRestart()}
                style={{ marginRight: 30 }}
              >
                重新开始
              </Button>
              <Button className='transform-button' type='primary'>
                <a href={getDownloadUrl(targetId)}>立即下载</a>
              </Button>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

export default NormalUpload
